/*
 * HttpResponse.cpp
 *
 *  Created on: 01/06/2014
 *      Author: vitor
 */

#include "HttpResponse.h"

HttpResponse::HttpResponse(TCPSocket socket, ResponseStatus status) :
		socket(socket), status(status) {
}

HttpResponse::~HttpResponse() {
}

void HttpResponse::add_header(const char* name, const char* value) {
	headers[std::string(name)] = std::string(value);
}

void HttpResponse::set_data(std::vector<char> data) {
	char data_size_string[100];

	sprintf(data_size_string, "%d", (int) data.size());
	headers[std::string("Content-Length")] = std::string(data_size_string);

	this->data.insert(this->data.end(), data.begin(), data.end());
}

void HttpResponse::write_bytes(std::vector<char>& response,
		const char* data_to_write, int data_size) {
	response.insert(response.end(), data_to_write, data_to_write + data_size);
}

void HttpResponse::get_status_string(char* result) {
	switch (status) {
	case OK:
		strcpy(result, "OK");
		break;
	case NOT_FOUND:
		strcpy(result, "Not Found");
		break;
	case SEE_OTHER:
		strcpy(result, "See Other");
		break;
	default:
		strcpy(result, "");
		break;
	}
}

void HttpResponse::write_status_line(std::vector<char>& response) {
	// Escreve a versão HTTP.
	write_bytes(response, "HTTP/1.1", strlen("HTTP/1.1"));

	char auxiliary_string[100];
	char temp_string[100];

	// Escreve o código de status (ex.: 200, 404)
	sprintf(auxiliary_string, " %d ", status);
	write_bytes(response, auxiliary_string, strlen(auxiliary_string));

	// Escreve o nome legível do status
	get_status_string(temp_string);
	sprintf(auxiliary_string, "%s\r\n", temp_string);
	write_bytes(response, auxiliary_string, strlen(auxiliary_string));
}

void HttpResponse::write_headers(std::vector<char>& response) {
	for (auto& header : headers) {
		char temp_string[200];

		sprintf(temp_string, "%s: %s\r\n", header.first.c_str(),
				header.second.c_str());
		write_bytes(response, temp_string, strlen(temp_string));
	}
}

// Escreve no par�metro os dados da response
void HttpResponse::write_data(std::vector<char>& response) {
	write_bytes(response, "\r\n", strlen("\r\n"));
	response.insert(response.end(), data.begin(), data.end());
}

void HttpResponse::send_response() {
	std::vector<char> response;

	write_status_line(response);
	write_headers(response);
	write_data(response);

	socket.send(response);
}
